package com.muk.meis.model.service;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import com.muk.meis.model.bean.UserProfile;

public class UserService {
	private UserProfile userPassLogin;

	public UserService() {
	}

	public boolean loginUser(String userName, String passWord) {
		EntityManagerFactory emf = Persistence
				.createEntityManagerFactory("meis");
		EntityManager em = emf.createEntityManager();
		List<UserProfile> lst = em.createQuery(
				"select e from UserProfile e where e.userName = '" + userName
						+ "' and e.password = '" + passWord + "'")
				.getResultList();
		if (lst.size() == 0)
			return false;
		else {
			this.userPassLogin = lst.get(0);			
			return true;
		}
	}
	
	public UserProfile getUserPassLoginDetail(){
		return userPassLogin;
	}

	public List<UserProfile> getUserList() {
		EntityManagerFactory emf = Persistence
				.createEntityManagerFactory("meis");
		EntityManager em = emf.createEntityManager();
		List<UserProfile> lst = em.createQuery("select e from UserProfile e")
				.getResultList();
		return lst;
	}

	public UserProfile getUserDetail(int userId){
		EntityManagerFactory emf = Persistence
				.createEntityManagerFactory("meis");
		EntityManager em = emf.createEntityManager();
		List<UserProfile> lst = em.createQuery("select e from UserProfile e where e.userId = "+userId,UserProfile.class).getResultList();
		return lst.get(0);
	}
	
	public String update(UserProfile userProfile){
		EntityManagerFactory emf = Persistence
				.createEntityManagerFactory("meis");
		EntityManager em = emf.createEntityManager();
		List<UserProfile> lst = em.createQuery("select e from UserProfile e where e.userId = "+userProfile.getUserId(),UserProfile.class).getResultList();
		UserProfile existUserProfile = lst.get(0);
		existUserProfile.setUserName(userProfile.getUserName());
		existUserProfile.setPassword(userProfile.getPassword());
		
		EntityTransaction t = em.getTransaction();
		t.begin();
		em.persist(existUserProfile);
		t.commit();
		
		return "operation complete";
	}
	
	public String create(UserProfile userProfile){
		EntityManagerFactory emf = Persistence
				.createEntityManagerFactory("meis");
		EntityManager em = emf.createEntityManager();
		EntityTransaction t = em.getTransaction();
		
		userProfile.setCreateDate(new Date());
		t.begin();
		em.persist(userProfile);
		t.commit();
		return null;
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		UserService obj = new UserService();
		List<UserProfile> lst = obj.getUserList();
		System.out.println(lst);
	}

}
